package com.leader.life.ext

import android.content.Context
import android.content.Intent
import android.net.Uri
import android.util.Log
import android.widget.Toast

/**
 * 判断 用户是否安装支付宝客户端
 */
fun Context.isAliPayInstalled(): Boolean {
    var uri = Uri.parse("alipays://platformapi/startApp")
    var intent = Intent(Intent.ACTION_VIEW, uri)
    var componentName = intent.resolveActivity(getPackageManager())
    return componentName != null
}

/**
 * 判断 用户是否安装微信客户端
 */
fun Context.isWeixinAvilible(): Boolean {
    val packageManager = getPackageManager() // 获取packagemanager
    var pinfo = packageManager.getInstalledPackages(0) // 获取所有已安装程序的包信息
    if (pinfo != null) {
        for (item in pinfo) {
            val packageName = item.packageName
            Log.e("包名", packageName)
            if (packageName.equals("com.tencent.mm")) {
                return true
            }
        }
    }
    return false
}

/**
 * 显示toast
 */
fun Context.toast(info: String) {
    Toast.makeText(this, info, Toast.LENGTH_SHORT).show()
}

/**
 * 显示toast
 */
fun Context.toast(infoRes: Int) {
    Toast.makeText(this, resources.getText(infoRes), Toast.LENGTH_SHORT).show()
}

/**
 * 是否安装
 */
fun Context.isInstalled(uri: String): Boolean {
    when {
        uri.startsWith("alipay") -> {
            if (!isAliPayInstalled()) {
                toast("检测到您的客户端未安装支付宝客户端")
                return false
            }
        }
        uri.startsWith("weixin") -> {
            if (!isWeixinAvilible()) {
                toast("检测到您的客户端未安装微信客户端")
                return false
            }
        }
    }
    return true
}